<?php
add_action('widgets_init', 'register_top_rate_coupons_widget');

function register_top_rate_coupons_widget()
{
	register_widget('top_rate_coupons');
}
class top_rate_coupons extends WP_Widget // widget class
{
	function top_rate_coupons() // widget setting | class name must be same function name
	{
		$widget_ops = array('classname' => 'top-rate-coupon-w', 'description' =>
				'Display top rate coupons - Store detail');
		$control_ops = array(
			'width' => 250,
			'height' => 350,
			'id_base' => 'top_rate_coupons');
		$this->WP_Widget('top_rate_coupons', 'CouponX - Top rate coupons', $widget_ops, $control_ops);
	}
	function widget($args, $instance) // display widget
	{
		extract($args);
        if(is_singular('store'))
        {
            global $post;
            $st_id = $post->ID;
        }        
		$title = apply_filters('widget_title', $instance['title']);
        $number_show = $instance['number_show'];
        if(!$number_show)
            $number_show = 1;
        
        $top_cp = cpx_get_top_cp_rate($st_id, $number_show);
        if($top_cp != null){
        ?>
            <div class="row-fluid boxf">
                <div class="row-fluid top-rate header-coupon">
                    <div class="span12 code-coupon">
                        <h2><?php echo strtoupper($title.' '.get_option('cpx_store_prefix')); ?></h2>
                    </div>
                </div>
           <?php 
                foreach ($top_cp as $p) {
                    $comment_count = wp_count_comments($p);
                    cpx_get_coupon_detail($p, $comment_count->total_comments);
                }
           ?>
            </div>
<?php  
        }
	}
    
	function update($new_instance, $old_instance) // update widget
	{
		$instance = $old_instance;		
        $instance['title'] = $new_instance['title'];
        $instance['number_show'] = $new_instance['number_show'];
        
		return $instance;
	}
    
	function form($instance) // form for the widget options
	{
?>
        <div style="color: #333;">
    		<p>        
    			<label for="<?php echo $this->get_field_id('title');?>"><?php echo 'Title'; ?></label>
    			<input type="text" id="<?php echo $this->get_field_id('title'); ?>" name="<?php	echo $this->get_field_name('title');?>" value="<?php echo $instance['title'];?>" style="width:100%;" />
    		</p>
            <p>
    			<label for="<?php echo $this->get_field_id('number_show');?>"><?php echo 'Number of coupons to show (default 1)';?></label>
    			<input type="text" id="<?php echo $this->get_field_id('number_show');?>" name="<?php echo $this->get_field_name('number_show');?>" value="<?php echo $instance['number_show'];?>" style="width:60%;" />
    		</p>
            	     
        </div>
<?php
	}
}
?>
